<?php

namespace app\admin\controller\admin;

use app\common\controller\AdminController;
use app\common\services\annotation\ControllerAnnotation;
use app\common\services\annotation\NodeAnnotation;
use support\Request;
use support\Response;

/**
 * @ControllerAnnotation(title="payment_account")
 */
class PaymentAccountController extends AdminController
{

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\PaymentAccount();
    }

    /**
     * @NodeAnnotation(title="列表")
     */
    public function index(Request $request): Response
    {
        $type = $request->get('type');
        if (!$request->isAjax()) {
            return $this->fetch('', ['paymentAccountType' => $type]);
        }
        if ($request->input('selectFields')) {
            return $this->selectList();
        }
        list($page, $limit, $where) = $this->buildTableParams();
        // 兼容其他搜索模式
        $type = $request->get('type', '');
        if (!empty($type)) {
            $where[] = ['type', '=', $type];
        }
        if (empty($where)) {
            $name = $request->get('name', '');
            if (!empty($name)) {
                $where[] = ['name', 'LIKE', '%'.$name.'%'];
            }
        }
        $count = $this->model->where($where)->count();
        $list  = $this->model->where($where)->order($this->order)->page($page, $limit)->select()->toArray();
        $data  = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }

    /**
     * @NodeAnnotation(title="添加")
     */
    public function add(Request $request): Response
    {
        if ($request->isAjax()) {
            $post = $request->post();
            try {
                $post['type'] = $request->get('type');
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                return $this->error('保存失败:' . $e->getMessage());
            }
            return $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnnotation(title="编辑")
     */
    public function edit(Request $request)
    {
        $id  = (int)$request->input('id');
        $row = $this->model->find($id);
        if (empty($row)) return $this->error('数据不存在');
        if ($request->isAjax()) {
            $post = $request->post();
            try {
                $post['type'] = $request->get('type');
                $save = $row->save($post);
            } catch (\PDOException|\Exception $e) {
                return $this->error('保存失败:' . $e->getMessage());
            }
            return $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign(compact('row'));
        return $this->fetch();
    }
}
